import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.cluster import KMeans

X = np.asarray(pd.read_csv('K-means.data'))
K = 7
model = KMeans(n_clusters=K)
y_pred = model.fit_predict(X)

cluster = model.fit(X)
centroid = cluster.cluster_centers_
print('选取的质心为：\n%s' % centroid)
color = ['blue', 'black', 'red', 'orange', 'green', 'purple', 'gray', 'yellow', 'pink']
fig, axi1 = plt.subplots(1)
for i in range(K):
    axi1.scatter(X[y_pred == i, 0], X[y_pred == i, 1],
                 marker='o',
                 s=8,
                 c=color[i])
axi1.scatter(centroid[:, 0], centroid[:, 1], marker='x', s=100, c='black')
plt.show()

'''
# 原始代码
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt

X, y = make_blobs(n_samples=500,  # 500个样本
                  n_features=2,  # 每个样本2个特征
                  centers=4,  # 4个中心
                  random_state=1  # 控制随机性
                  )

color = ['red', 'pink', 'orange', 'gray']
fig, axi1 = plt.subplots(1)
for i in range(4):
    axi1.scatter(X[y == i, 0], X[y == i, 1],
                 marker='o',
                 s=8,
                 c=color[i]
                 )
plt.show()

from sklearn.cluster import KMeans

n_clusters = 3
cluster = KMeans(n_clusters=n_clusters, random_state=0).fit(X)
centroid = cluster.cluster_centers_
inertia = cluster.inertia_
color = ['red', 'pink', 'orange', 'gray']
fig, axi1 = plt.subplots(1)
for i in range(n_clusters):
    axi1.scatter(X[cluster == i, 0], X[cluster == i, 1],
                 marker='o',
                 s=8,
                 c=color[i])
axi1.scatter(centroid[:, 0], centroid[:, 1], marker='x', s=100, c='black')
'''
